<template>
  <div>
    <div ref="pieChart" :style="{ width: '400px', height: '300px' }"></div>
  </div>
</template>
<script setup lang="ts">
import * as echarts from 'echarts';
import { onMounted, ref } from 'vue';
const props = defineProps({
  chartData: {
    type: Array,
    default: () => []
  },
  chartDataTotal: {
    type: Number,
    default: 0
  }
});

// const chartData = ref([
//   { value: 60, name: '正常' },
//   { value: 10, name: '偏高' },
//   { value: 30, name: '偏低' }
// ]);
//绘制饼图
const option = {
  tooltip: {
    trigger: 'item'
  },
  legend: {
    orient: 'vertical',
    top: 'center',
    right: '2%',
    formatter: function (name: any) {
      //该函数用于设置图例显示后的百分比
      let total = 0;
      let value = 0;
      props.chartData.forEach((item: any) => {
        total += Number(item.value);
        if (item.name == name) {
          value = item.value;
        }
      });
      if(value==0 && total==0){
        return `${name} ${value}次 (0%)`; //返回出图例所显示的内容是名称+百分比
      }else{
        var p = Math.round((value / total) * 100); //求出百分比
        return `${name} ${value}次 (${p}%)`; //返回出图例所显示的内容是名称+百分比
      }
      
    }
  },
  title: {
          zlevel: 0,
          text: [
            '{value|' +props.chartDataTotal + '}',
          ].join('\n'),
          top: 'center',
          left: '34%',
          textAlign: 'center',
          textStyle: {
            rich: {
              value: {
                color: '#303133',
                fontSize: 20,
                fontWeight: 'bold',
                lineHeight: 50
              }
            }
          }
        },
  series: [
    {
      name: '指标',
      type: 'pie',
      radius: ['30%', '50%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderColor: '#fff',
        borderWidth: 0
      },
      label: {
        show: false,
        position: 'center'
      },
      // emphasis: {
      //   label: {
      //     show: true,
      //     fontSize: 14,
      //     fontWeight: 'bold'
      //   }
      // },
      labelLine: {
        show: false
      },
      data: props.chartData,
      center: ['35%', '50%']
    }
  ]
};
const pieChart = ref<HTMLElement>();
const myChart2 = ref<any>();
function initPieEcharts() {
  myChart2.value = echarts.init(pieChart.value!);
  myChart2.value.setOption(option);
}

onMounted(() => {
  initPieEcharts();
});
</script>
